package com.example.zg.learn.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.zg.learn.R;

import java.util.ArrayList;
import java.util.List;

/**
 * 描述：
 * zhougan
 * 2019/1/18
 **/
public class BookcaseFragment extends BaseFragment {
    private static final String TAG = "BookcaseFragment>>>";
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private List<Fragment> fragments;
    private ViewPagerAdapter mVpAdapter;
    private String[] titles={"书架","关注"};

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_basecase,container,false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        initView(view);
    }

    private void initFragments(){
        //这里可以直接添加Fragment 不需要用 fragmentManager.find
        //因为用的FragmentPagerAdapter来加载数据没在这个接口中做了判断的(先find如果不存在再 getItem)
        Log.i(TAG, "initFragments: 书架和关注");
        fragments=new ArrayList<>();
        fragments.add(new BookListFragment());
        fragments.add(new GuanzhuFragment());
    }

    private void initView(View view){
        mTabLayout=view.findViewById(R.id.tabLayout);
        mViewPager=view.findViewById(R.id.viewPager);

        initFragments();

        mVpAdapter=new ViewPagerAdapter(getChildFragmentManager());
        mViewPager.setAdapter(mVpAdapter);

        mTabLayout.setupWithViewPager(mViewPager);
    }

    private class ViewPagerAdapter extends FragmentPagerAdapter{

        private ViewPagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        @Nullable
        @Override
        public CharSequence getPageTitle(int position) {
            return titles[position];
        }
    }

}
